package com.fenghongzhang.day006;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;

import java.util.List;

public class MyVPAdapter extends PagerAdapter {

    private Context context;
    private List<String> list;

    public MyVPAdapter(Context context, List<String> list) {
        this.context = context;
        this.list = list;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }

    //移除一个页面
    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        // 注释掉,有些版本会报错.
//        super.destroyItem(container, position, object);
        container.removeView((View) object);
    }

    /**
     * 生成每一页的
     * @param container vp
     * @param position 下标
     * @return
     */
    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        View inflate = LayoutInflater.from(context).inflate(R.layout.vp_layout, null);
        //是给布局中的view改值
        TextView textView = inflate.findViewById(R.id.vp_text);
        textView.setText(list.get(position));

        //把创建出来的view和container
        container.addView(inflate);
        return inflate;
    }
}
